package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

/**refreshDetailData
 * A simple {@link Fragment} subclass.
 */
public class FragmentCheck extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_GetPartOver = 1002;
    public static final int MSG_GetDiffOver =1003;
    public static final int MSG_GetWorkInfoOver =1004;
    public static final int MSG_SaveOver=1005;
    public static final int MSG_GetPlaceOver=1006;
    public static final int MSG_GetRecordOver=1007;
    private BasePopupWindow taskPopupWindow;
    public static final int MSG_SCANBARCODE = 9001;
    public static final int MSG_DETAIL = 9002;
    public static final int MSG_PROCRESULT=9003;
    public static final int MSG_NoData=9004;
    LinearLayout outerLinear;
    //全局变量
    SQLiteDatabase tmpdb;
    public static String TAG= FragmentCheck.class.getName();
    //用于将Activity中的参数传给Fragment
    private Map<String, Object> fragmentParams = new HashMap<String, Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curLoginUserNo, curLoginUser, curServiceUrl = "",curServiceDir="",curDepartNo, curDepart, CPUID="", PrBarcode = "";
    String curStyleID="";
    EditText edt_barcode;
    Button btn_find,btn_Query,btn_edit;
    ImageButton btn_editBarcode;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_StyleSort,txt_PO,txt_Color, txt_PartName,txt_Size,txt_PackNo,txt_Number,txt_TodayBadNum;
    String CurFormNo="";
    //Measure
    Button view_viewBtn,view_submitBtn;
    LinearLayout liner_BtnPlace;
    TextView view_QuestionType,view_Question,view_WorkName, view_Place,txt_TodayCheckNum,txt_TodayRepairNum;
    GridView placeGrid,typeGrid, questionGrid;
    ListView procList,recordList;
    //其他变量
    JSONArray resultJSON,detailJSON, typeJSON,diffJSON,procJSON,questionJSON,recordJSON,placeJSON;
    private ProgressDialog waitDialog = null;
    RecordListAdapter recordListAdapter;
    String language="";
    Integer PackSerNo;
    String SelPartName,SelDiff,SelQuestionName,SelEmpNo,SelEmpName,SelWorkNo,SelWorkName, SelPlace;
    int OKNum=0,BadNum=0,IronNum=0,RemakeNum=0,PackNum=0;
    String PieceID=java.util.UUID.randomUUID().toString();

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public FragmentCheck() {
        // Required empty public constructor
    }



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity = (MainActivity) getActivity();
        mainHandler = activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerCheck(new MainActivity.OnTransParamsListenerCheck() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams != null) {
                    try {
                        String paramComm = mParams.get("ParamComm").toString();
                        if (paramComm == "LoginParam") {
                            Log.d(this.getClass().getName(), "LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo = mParams.get("LoginUserNo").toString();
                            curLoginUser = mParams.get("LoginUser").toString();
                            curServiceUrl = mParams.get("ServiceUrl").toString();
                            curServiceDir= mParams.get("ServiceDir").toString();
                            curDepartNo = mParams.get("DepartNo").toString();
                            curDepart = mParams.get("Depart").toString();
                            CPUID = mParams.get("CPUID").toString();
                            language= mParams.get("language").toString();
                            Log.d(this.getClass().getName(), "LoginParam------------------>2");
                            //发消息置焦点
                            Message msg = new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        if (tmpdb==null) OpenCreateDB();
        recordListAdapter = new RecordListAdapter(getContext());
        try {
            placeJSON=new JSONArray("[]");
            typeJSON=new JSONArray("[]");
            questionJSON=new JSONArray("[]");
            procJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //打开数据库
    public void OpenCreateDB(){
        if (tmpdb==null) {
            MainActivity activity = (MainActivity) getActivity();
            tmpdb = activity.mainDB;
        }
    }
    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null) {
                //任意消息来均置焦点
                if (edt_barcode.isFocused()==false) setEditBarcodeFocus();
                else edt_barcode.selectAll();
                if (waitDialog.isShowing()==true) waitDialog.cancel();
                //消息处理;
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case MSG_SaveOver:
                        transResult();
                        break;
                    case MSG_SCANBARCODE:
                        fillFormtext(detailJSON);
                        break;
                    case MSG_GetRecordOver:
                        showTask();
                        break;
                    case MSG_GetPartOver:
                        //显示部件;
                        PartGridAdapter partGridAdapter=new PartGridAdapter(getContext());
                        typeGrid.setAdapter(partGridAdapter);
                        break;
                    case MSG_GetDiffOver:
                        //显示按钮;
                        ShowDiffBtn();
                        break;
                    case MSG_GetWorkInfoOver:
                        //显示部件;
                        ProcGridAdapter procGridAdapter=new ProcGridAdapter(getContext());
                        procList.setAdapter(procGridAdapter);
                        break;
                    case MSG_GetPlaceOver:
                        //显示部件;
                        PlaceGridAdapter placeGridAdapter=new PlaceGridAdapter(getContext());
                        placeGrid.setAdapter(placeGridAdapter);
                        break;
                    case MSG_PROCRESULT:
                        String resultMsg = null;
                        try {
                            resultMsg = procJSON.optJSONObject(0).getString("PROCRESULT");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //提示提交完成，需确认;
                        // 创建对话框
                        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                .setTitle(getString(R.string.SystemHint)).setMessage(resultMsg)
                                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        hideBottomUIMenu();
                                    }
                                }).create();
                        alertDialog.show(); // 显示对话框
                        break;
                    default:
                        break;
                }
            }
        }
    };

    private void transResult() {
        try {
            ClearSelInfo();
            if (resultJSON.getJSONObject(0).has("TodayCheckNum")==true) txt_TodayCheckNum.setText(resultJSON.getJSONObject(0).getString("TodayCheckNum"));
            if (resultJSON.getJSONObject(0).has("TodayRepairNum")==true) txt_TodayRepairNum.setText(resultJSON.getJSONObject(0).getString("TodayRepairNum"));
            if (resultJSON.getJSONObject(0).has("TodayBadNum")==true) txt_TodayBadNum.setText(resultJSON.getJSONObject(0).getString("TodayBadNum"));
            if (resultJSON.getJSONObject(0).has("Number")==true) {
                txt_Number.setText(resultJSON.getJSONObject(0).getString("Number"));
                PackNum=Integer.parseInt(resultJSON.getJSONObject(0).getString("Number"));
            }
            if (resultJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("HintInfo"));
            if (resultJSON.getJSONObject(0).has("NeedGetPart")==true) {
                if (resultJSON.getJSONObject(0).getString("NeedGetPart").toUpperCase().equals("Y")){
                    GetPart(curStyleID,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                };
            }
            if (resultJSON.getJSONObject(0).has("NeedGetDiff")==true) {
                if (resultJSON.getJSONObject(0).getString("NeedGetDiff").toUpperCase().equals("Y")){
                    GetDiff(curStyleID,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                };
            }
            if (resultJSON.getJSONObject(0).has("NeedGetPlace")==true) {
                if (resultJSON.getJSONObject(0).getString("NeedGetPlace").toUpperCase().equals("Y")){
                    GetPlace(curStyleID,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                };
            }
            if (resultJSON.getJSONObject(0).has("ErrInfo") == true) {
                //MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), R.raw.warn);
                //mediaPlayer.start();
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                        .setTitle(getString(R.string.SystemHint)).setMessage(resultJSON.getJSONObject(0).getString("ErrInfo"))
                        .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                hideBottomUIMenu();
                                return;
                            }
                        }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
            }
            if (resultJSON.getJSONObject(0).has("ResultInfo") == true) {
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                        .setTitle(getString(R.string.SystemHint)).setMessage(resultJSON.getJSONObject(0).getString("ErrInfo"))
                        .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                hideBottomUIMenu();
                                return;
                            }
                        }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //动态创建尺寸差异按钮
    private void ShowDiffBtn() {
        int childCount = liner_BtnPlace.getChildCount();
        for (int i = childCount - 1; i >= 0; i--) {
            View view = liner_BtnPlace.getChildAt(i);
            if ((view instanceof TextView)||(view instanceof View)) {
                liner_BtnPlace.removeViewAt(i);
            }
        }
        if (diffJSON!=null){
            for (int i=0;i<diffJSON.length();i++){
                if (diffJSON.optJSONObject(i).has("DiffIdent")&&diffJSON.optJSONObject(i).has("DiffInfo")){
                    try {
                        Button tmpBtn = new Button(getContext());
                        LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams((int) WRAP_CONTENT, MATCH_PARENT, 1);
                        layoutParams.setMarginStart(4);
                        tmpBtn.setTextColor(getResources().getColor(R.color.white));
                        tmpBtn.setTextSize(18);
                        if (diffJSON.optJSONObject(i).getString("DiffInfo").equals("Error"))
                            tmpBtn.setBackground(getResources().getDrawable(R.drawable.btn_defaultwarn));
                        else
                            tmpBtn.setBackground(getResources().getDrawable(R.drawable.btn_default));
                        tmpBtn.setText(diffJSON.optJSONObject(i).getString("DiffIdent"));
                        tmpBtn.setOnClickListener(this);
                        tmpBtn.setTag(diffJSON.optJSONObject(i).getString("DiffInfo")+":"+diffJSON.optJSONObject(i).getString("DiffIdent"));
                        liner_BtnPlace.addView(tmpBtn,layoutParams);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }


    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_check, container, false);
        initView(root);
        System.out.println(this.getClass().getName() + "_onCreateView");
        return root;
    }

    private void initView(View view) {
        outerLinear=view.findViewById(R.id.outerLinear);
        //条码相关;
        view.findViewById(R.id.view_newBtn).setOnClickListener(this);
        btn_edit=(Button)view.findViewById(R.id.btn_edit);
        btn_edit.setOnClickListener(this);
        btn_find=(Button)view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Query=(Button)view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_editBarcode=(ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        barcodeFind(v);
                    }

                }
                return false;
            }
        });
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_PO=view.findViewById(R.id.txt_PO);
        txt_Color=view.findViewById(R.id.txt_Color);
        txt_PartName =view.findViewById(R.id.txt_PartName);
        txt_Size=view.findViewById(R.id.txt_Size);
        txt_PackNo=view.findViewById(R.id.txt_PackNo);
        txt_StyleSort=view.findViewById(R.id.txt_StyleSort);
        txt_Number=view.findViewById(R.id.txt_Number);
        txt_TodayBadNum=view.findViewById(R.id.txt_TodayBadNum);
        txt_TodayCheckNum=view.findViewById(R.id.txt_TodayCheckNum);
        txt_TodayRepairNum=view.findViewById(R.id.txt_TodayRepairNum);
        view_viewBtn=view.findViewById(R.id.view_viewBtn);
        view_viewBtn.setOnClickListener(this);
        view_submitBtn=view.findViewById(R.id.view_submitBtn);
        view_submitBtn.setOnClickListener(this);
        liner_BtnPlace =view.findViewById(R.id.liner_BtnPlace);
        liner_BtnPlace.setOnClickListener(this);
        view_QuestionType =view.findViewById(R.id.view_QuestionType);
        view_Question =view.findViewById(R.id.view_Question);
        view_Place =view.findViewById(R.id.view_Place);
        view_WorkName =view.findViewById(R.id.view_WorkName);

        typeGrid =view.findViewById(R.id.typeGrid);
        typeGrid.setOnItemClickListener(this);

        placeGrid =view.findViewById(R.id.placeGrid);
        placeGrid.setOnItemClickListener(this);
        questionGrid=view.findViewById(R.id.questionGrid);
        questionGrid.setOnItemClickListener(this);
        procList=view.findViewById(R.id.procList);
        procList.setOnItemClickListener(this);
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
        //提示框pd=new ProgressDialog(this);
        waitDialog = new ProgressDialog(getActivity());
        waitDialog.setTitle(getString(R.string.SystemHint));
    }

    private void barcodeFind(View v) {
        hideIM(v);
        if (edt_barcode.getText().length()==0) {
            curToast.setText(getString(R.string.PleaseInputBarcode));
            curToast.show();
        }
        String CurPage;

        //执行查询;
        scanBarcodeData(edt_barcode.getText().toString(),CurFormNo,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),"2");
        //未有焦点
        if (edt_barcode.isFocused()==false){
            //发消息置焦点
            Message msg =new Message();
            msg.what = msgFocusBarcode;
            fragmentHandler.removeMessages(msg.what);
            fragmentHandler.sendMessage(msg);
        } else edt_barcode.selectAll();
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }
    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }

    //根据卡号或条码刷新数据;
    private void scanBarcodeData(String BarcodeParam, String FormNoParam,String OrderNoParam, String StyleNoParam, String CurPageParam) {
        playRingtone();
        PrBarcode = BarcodeParam;
        PieceID=java.util.UUID.randomUUID().toString();
        try {
            detailJSON = new JSONArray("[]");
            procJSON=new JSONArray("[]");
            //清除界面显示内容;
            clearFormText();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_OneCheckBarcode @Barcode='" + BarcodeParam + "',@FormNo='" + FormNoParam
                + "',@OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam
                + "',@OPERTYPE='SCANBARCODE',@CurPage='" + CurPageParam + "',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //刷新缸布列表;
    private void editPackNo(String BarcodeParam,String NumberParam)
    {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_OneCheckBarcode @Barcode='" + BarcodeParam + "',@NewNumber='" + NumberParam  + "',@OPERTYPE='SCANBARCODE',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    //修改包件数;
    private void showEditPakcNum(String paramNum ){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("件数更改");
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(getContext()).inflate(R.layout.input_num, null);
        //    设置我们自己定义的布局文件作为弹出框的Content
        builder.setView(view);
        final EditText edt_oldNum =view.findViewById(R.id.edt_oldNum);
        edt_oldNum.setText(paramNum);
        final EditText edt_newNum = view.findViewById(R.id.edt_newNum);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                String a = edt_oldNum.getText().toString().trim();
                String b = edt_newNum.getText().toString().trim();
                if (b.length()>0) editPackNo(PrBarcode,b);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {

            }
        });
        builder.show();
    }



    //清除界面显示内容
    private void clearFormText() {
        txt_OrderNo.setText("");
        txt_StyleNo.setText("");
        txt_PO.setText("");
        txt_Color.setText("");
        txt_PackNo.setText("");
        txt_Size.setText("");
        txt_StyleSort.setText("");
        txt_Number.setText("");
        txt_TodayBadNum.setText("");
        txt_TodayCheckNum.setText("");
        txt_TodayRepairNum.setText("");
        txt_HintInfo.setText("");
        try {
            procJSON=new JSONArray("[]");
            questionJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //显示部件;
        //显示部件;
        //显示部件;
        PlaceGridAdapter placeGridAdapter=new PlaceGridAdapter(getContext());
        placeGrid.setAdapter(placeGridAdapter);
        QuestionGridAdapter questionGridAdapter=new QuestionGridAdapter(getContext());
        questionGrid.setAdapter(questionGridAdapter);
        PartGridAdapter partGridAdapter=new PartGridAdapter(getContext());
        typeGrid.setAdapter(partGridAdapter);
        ProcGridAdapter procGridAdapter=new ProcGridAdapter(getContext());
        procList.setAdapter(procGridAdapter);
    }

    //填充界面显示内容;
    private void fillFormtext(JSONArray paramJSON) {
        if (paramJSON.length() > 0) {
            try {
                System.out.println("1");
                ClearRecord();
                if (paramJSON.getJSONObject(0).has("StyleID")==true) curStyleID=paramJSON.getJSONObject(0).getString("StyleID");
                if (paramJSON.getJSONObject(0).has("FormNo") == true) CurFormNo=paramJSON.getJSONObject(0).getString("FormNo");
                if (paramJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(paramJSON.getJSONObject(0).getString("OrderNo"));
                if (paramJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(paramJSON.getJSONObject(0).getString("StyleNo"));
                if (paramJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(paramJSON.getJSONObject(0).getString("PO"));
                if (paramJSON.getJSONObject(0).has("Color")==true) txt_Color.setText(paramJSON.getJSONObject(0).getString("Color"));
                if (paramJSON.getJSONObject(0).has("PackNo")==true) txt_PackNo.setText(paramJSON.getJSONObject(0).getString("PackNo"));
                if (paramJSON.getJSONObject(0).has("Size")==true) txt_Size.setText(paramJSON.getJSONObject(0).getString("Size"));
                if (paramJSON.getJSONObject(0).has("StyleSort")==true) txt_StyleSort.setText(paramJSON.getJSONObject(0).getString("StyleSort"));
                if (paramJSON.getJSONObject(0).has("TodayCheckNum")==true) txt_TodayCheckNum.setText(paramJSON.getJSONObject(0).getString("TodayCheckNum"));
                if (paramJSON.getJSONObject(0).has("TodayRepairNum")==true) txt_TodayRepairNum.setText(paramJSON.getJSONObject(0).getString("TodayRepairNum"));
                if (paramJSON.getJSONObject(0).has("TodayBadNum")==true) txt_TodayBadNum.setText(paramJSON.getJSONObject(0).getString("TodayBadNum"));
                if (paramJSON.getJSONObject(0).has("Number")==true) {
                    txt_Number.setText(paramJSON.getJSONObject(0).getString("Number"));
                    PackNum=Integer.parseInt(paramJSON.getJSONObject(0).getString("Number"));
                }
                if (paramJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(paramJSON.getJSONObject(0).getString("HintInfo"));
                if (paramJSON.getJSONObject(0).has("NeedGetPart")==true) {
                    if (paramJSON.getJSONObject(0).getString("NeedGetPart").toUpperCase().equals("Y")){
                        GetPart(curStyleID,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                    };
                }
                if (paramJSON.getJSONObject(0).has("NeedGetDiff")==true) {
                    if (paramJSON.getJSONObject(0).getString("NeedGetDiff").toUpperCase().equals("Y")){
                        GetDiff(curStyleID,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                    };
                }
                if (paramJSON.getJSONObject(0).has("NeedGetPlace")==true) {
                    if (paramJSON.getJSONObject(0).getString("NeedGetPlace").toUpperCase().equals("Y")){
                        GetPlace(curStyleID,txt_OrderNo.getText().toString(),txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                    };
                }
                if (paramJSON.getJSONObject(0).has("ErrInfo") == true) {
                    //MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(), R.raw.warn);
                    //mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(getString(R.string.SystemHint)).setMessage(paramJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (paramJSON.getJSONObject(0).has("ResultInfo") == true) {
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(getString(R.string.SystemHint)).setMessage(paramJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    //清除
    private void ClearSelInfo(){
        try {
            if (recordJSON==null) recordJSON=new JSONArray("[]");
            if (typeGrid.getAdapter()!=null) typeGrid.setAdapter(typeGrid.getAdapter());
            if (questionGrid.getAdapter()!=null) questionGrid.setAdapter(questionGrid.getAdapter());
            if (placeGrid.getAdapter()!=null) placeGrid.setAdapter(placeGrid.getAdapter());
            SelPartName ="";
            SelDiff="";
            SelQuestionName="";
            SelEmpNo="";
            SelEmpName="";
            SelWorkNo="";
            SelWorkName="";
            SelPlace="";
            RefreshNum();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    //清除
    private void ClearRecord(){
        try {
            if (recordJSON==null) recordJSON=new JSONArray("[]");
            SelPartName ="";
            SelDiff="";
            SelQuestionName="";
            SelEmpNo="";
            SelEmpName="";
            SelWorkNo="";
            SelWorkName="";
            SelPlace="";
            RefreshNum();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private void RefreshNum(){
        view_WorkName.setText(SelWorkName);
        view_Question.setText(SelQuestionName);
        view_QuestionType.setText(SelPartName);
        view_Place.setText(SelPlace);
    }
    //获取部位;
    private void GetPart(String paramStyleID, String paramOrderNo, String paramStyleNo, String paramStyleSort) {
        try {
            typeJSON = new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_OneCheckGetPart @StyleID='" + paramStyleID
                + "',@OrderNo='" + paramOrderNo + "',@StyleNo='" + paramStyleNo+ "',@StyleSort='" + paramStyleSort
                + "',@OperType='GetPart',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "',@LNG='"+language+"'";
        System.out.println(SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    //获取容差;
    private void GetDiff(String paramStyleID, String paramOrderNo, String paramStyleNo, String paramStyleSort) {
        try {
            diffJSON = new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_OneCheckGetDiff @StyleID='" + paramStyleID
                + "',@OrderNo='" + paramOrderNo + "',@StyleNo='" + paramStyleNo+ "',@StyleSort='" + paramStyleSort
                + "',@OperType='GetDiff',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "',@LNG='"+language+"'";
        System.out.println(SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    //获取容差;
    private void GetPlace(String paramStyleID, String paramOrderNo, String paramStyleNo, String paramStyleSort) {
        try {
            diffJSON = new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_OneCheckGetPlace @StyleID='" + paramStyleID
                + "',@OrderNo='" + paramOrderNo + "',@StyleNo='" + paramStyleNo+ "',@StyleSort='" + paramStyleSort
                + "',@OperType='GetPlace',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "',@LNG='"+language+"'";
        System.out.println(SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    //获取容差;
    private void GetWorkInfo(String paramBarcode, String paramPart) {
        try {
            procJSON = new JSONArray("[]");
            //显示部件;
            ProcGridAdapter procGridAdapter=new ProcGridAdapter(getContext());
            procList.setAdapter(procGridAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_OneCheckGetWorkInfo @Barcode='" + paramBarcode
                + "',@PartName='" + paramPart + "',@OperType='GetWorkInfo',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "',@LNG='"+language+"'";
        System.out.println(SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }

    //设置焦点到扫描输入框
    private void setEditBarcodeFocus() {
        //设置焦点
        System.out.println(TAG+" 设置焦点-------------------------------1.Start");
        if (edt_barcode != null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(TAG+" 设置焦点-------------------------------1.End");
    }

    @Override
    public void onStart() {
        super.onStart();
        setEditBarcodeFocus();
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        hideBottomUIMenu();
        switch (v.getId()) {
            case R.id.btn_Query:
                Intent intentQueryActivity=new Intent(getContext(),QueryActivity.class);
                Bundle paramBundle = new Bundle();
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "一检扫描查询");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                intentQueryActivity.putExtras(paramBundle);
                startActivity(intentQueryActivity);
                break;
            case R.id.btn_find:
                //隐藏键盘
                barcodeFind(v);
                break;
            case R.id.btn_edit:
                if (txt_Number.getText().toString().length()>0) showEditPakcNum(txt_Number.getText().toString());
                else {
                    curToast.setText("请先扫描包条码!");
                    curToast.show();
                }
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.view_viewBtn:
                try {
                    recordJSON = new JSONArray("[]");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                waitDialog.setTitle("正在从服务器获取数据....");
                waitDialog.show();
                //执行SQL过程
                String SqlComm="Exec KeyPoint_OneCheckGetRecord @OperType='GetRecord',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "',@LNG='"+language+"'";
                System.out.println(SqlComm);
                //调用WebService过程并处理界面更新;
                ReadSQLData(SqlComm);

                break;
            case R.id.view_newBtn:
                PieceID=java.util.UUID.randomUUID().toString();
                curToast.setText("新的一件开始");
                curToast.show();
                break;
            case R.id.view_submitBtn:
                SubmitRecord(PrBarcode, SelEmpNo,SelEmpName,SelWorkNo,SelWorkName, SelPartName,SelQuestionName,SelPlace,PieceID);
                break;
            case R.id.view_cancelBtn:
                break;
            case R.id.btn_PopRec:
                if (taskPopupWindow!=null) taskPopupWindow.dismiss();
                break;
            case R.id.btn_PopCancel:
                try {
                    recordJSON=new JSONArray("[]");
                    recordListAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            default:
                if (v.getTag() instanceof String){
                    System.out.println(v.getTag().toString());
                    SelDiff=v.getTag().toString();
                }
                break;
        }

    }


    //提交所选择的工序至服务器,然后刷新工序列表;
    private void SubmitRecord(final String paramBarcode, final String paramEmpNo, final String paramEmpName, final String paramWorkNo, final String paramWorkName, final String paramPartName, final String paramQuestionName, final String paramPlace,final String paramPieceID) {
        if ((SelPartName.length()==0)||(SelQuestionName.length()==0)){
            curToast.setText("请选择具体疵点问题!");
            curToast.show();
            return;
        }
        if (recordJSON == null) return;
        if (PrBarcode.length() == 0) {
            curToast.setText("请先扫描条码!");
            curToast.show();
            return;
        }
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String tmpCheckMaID = java.util.UUID.randomUUID().toString();
                //将数据读到JSONArray;
                try {
                    PreparedStatement pstmt = ToolUtil.getSQLConnection().prepareStatement(
                            "Insert into KeyPointCheckMa(CheckMaID,Barcode,EmpNo,EmpName,WorkNo,WorkName,PartName,QuestionName,Place,UserNo,UserName,CPUID,PieceID,CreateTime) values(?,?,?,?,?,?,?,?,?,?,?,?,?,getdate())");
                    pstmt.setString(1, tmpCheckMaID);
                    pstmt.setString(2, paramBarcode);
                    pstmt.setString(3, paramEmpNo);
                    pstmt.setString(4, paramEmpName);
                    pstmt.setString(5, paramWorkNo);
                    pstmt.setString(6, paramWorkName);
                    pstmt.setString(7, paramPartName);
                    pstmt.setString(8, paramQuestionName);
                    pstmt.setString(9, paramPlace);
                    pstmt.setString(10, curLoginUserNo);
                    pstmt.setString(11, curLoginUser);
                    pstmt.setString(12, CPUID);
                    pstmt.setString(13, paramPieceID);
                    pstmt.executeUpdate();
                    pstmt.close();
                    //调用存储过程;
                    SqlComm = " Exec KeyPoint_CheckSaveTrans @OperType='SaveTrans',@FormType='OneCheck',@CheckMaID='" + tmpCheckMaID + "',@PieceID='"+paramPieceID+"'";
                    ReadSQLData(SqlComm);
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        };
        new Thread(run).start();
    }



    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = ToolUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        String OperType="";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true) OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType")==true) OperType=jsonArray.optJSONObject(0).getString("OperType");
                        System.out.println("OperType:" + OperType);
                        if (OperType.toUpperCase().equals("SCANBARCODE")) {
                            detailJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SCANBARCODE;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OperType.equals("GetRecord")){
                            recordJSON=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_GetRecordOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (OperType.equals("GetDiff")){
                            diffJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_GetDiffOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        //疵点类别分解及显示
                        if (OperType.equals("GetPart")) {
                            tmpdb.execSQL("Delete from PartQuestion");
                            //保存工序数据;
                            for (int i=0;i<jsonArray.length();i++){
                                tmpdb.execSQL("INSERT INTO PartQuestion(PartNo,PartName,QuestionNo,QuestionName) " +
                                                "VALUES (?,?,?,?)",
                                        new Object[]{jsonArray.optJSONObject(i).getString("PartNo"), jsonArray.optJSONObject(i).getString("PartName")
                                                , jsonArray.optJSONObject(i).getString("QuestionNo"), jsonArray.optJSONObject(i).getString("QuestionName")
                                        });
                            }
                            //显示生产单相关信息;
                            Cursor curma = tmpdb.rawQuery("SELECT PartName  FROM PartQuestion  Group BY PartName",null);
                            if (curma.getCount()>0) {
                                typeJSON =new JSONArray("[]");
                                while (curma.moveToNext()) {
                                    JSONObject tmpObj = new JSONObject();
                                    tmpObj.put("PartName", curma.getString(curma.getColumnIndex("PartName")));
                                    typeJSON.put(tmpObj);
                                }
                                curma.close();
                            }
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_GetPartOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);

                        }
                        if (OperType.equals("GetPlace")){
                            placeJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_GetPlaceOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        //疵点类别分解及显示
                        if (OperType.equals("GetWorkInfo")) {
                            procJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_GetWorkInfoOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        //疵点类别分解及显示
                        if (OperType.equals("SaveTrans")) {
                            resultJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SaveOver;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                    } else{
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_NoData;
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }

        };
        new Thread(run).start();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent== typeGrid){
            if (typeJSON !=null) {
                try {
                    view_QuestionType.setText(typeJSON.optJSONObject(position).getString("PartName"));
                    SelPartName = view_QuestionType.getText().toString();
                    showQuestion(view_QuestionType.getText().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }
        if (parent==questionGrid){
            if (questionJSON!=null) {
                try {
                    view_Question.setText(questionJSON.optJSONObject(position).getString("QuestionName"));
                    SelQuestionName=view_Question.getText().toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }
        if (parent==placeGrid){
            if (placeJSON!=null){
                try {
                    SelPlace=placeJSON.optJSONObject(position).getString("PlaceName");
                    view_Place.setText(SelPlace);
                    GetWorkInfo(PrBarcode, view_Place.getText().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        if (parent==procList){
            if (procJSON!=null) {
                try {
                    view_WorkName.setText(procJSON.optJSONObject(position).getString("WorkName"));
                    if (procJSON.optJSONObject(position).has("WorkNo")) SelWorkNo=procJSON.optJSONObject(position).getString("WorkNo");
                    if (procJSON.optJSONObject(position).has("WorkName")) SelWorkName=procJSON.optJSONObject(position).getString("WorkName");
                    if (procJSON.optJSONObject(position).has("EmpNo")) SelEmpNo=procJSON.optJSONObject(position).getString("EmpNo");
                    if (procJSON.optJSONObject(position).has("EmpName")) SelEmpName=procJSON.optJSONObject(position).getString("EmpName");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    private void showQuestion(String paramQuestion) {
        try {
            //显示生产单相关信息;
            Cursor curma = tmpdb.rawQuery("SELECT QuestionNo,QuestionName  FROM PartQuestion where PartName=? Order by QuestionNo",new String[]{paramQuestion});
            if (curma.getCount()>0) {
                questionJSON=new JSONArray("[]");
                while (curma.moveToNext()) {
                    JSONObject tmpObj = new JSONObject();
                    tmpObj.put("QuestionNo", curma.getString(curma.getColumnIndex("QuestionNo")));
                    tmpObj.put("QuestionName", curma.getString(curma.getColumnIndex("QuestionName")));
                    questionJSON.put(tmpObj);
                }
                curma.close();
            }
            QuestionGridAdapter questionGridAdapter=new QuestionGridAdapter(getContext());
            questionGrid.setAdapter(questionGridAdapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //显示任务
    private void showTask() {
        int deviationX=300,deviationY=120;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        System.out.println("屏宽:" + dm.widthPixels);
        System.out.println("屏高:" + dm.heightPixels);
        //创建并初始化完成
        //创建并初始化完成
        if (taskPopupWindow ==null) {
            taskPopupWindow = new BasePopupWindow(getContext());
            taskPopupWindow.setWidth(dm.widthPixels-deviationX);
            taskPopupWindow.setHeight(dm.heightPixels-deviationY);
        }
        //取视图
        View popView=LayoutInflater.from(getContext()).inflate(R.layout.fragment_check_record, null);
        recordList=popView.findViewById(R.id.recordList);
        LinearLayout linerCardTitle=popView.findViewById(R.id.linerCardTitle);
        if (recordJSON!=null) {
            recordList.setAdapter(recordListAdapter);
        }
        ((Button)popView.findViewById(R.id.btn_PopRec)).setOnClickListener(this);
        ((Button)popView.findViewById(R.id.btn_PopCancel)).setOnClickListener(this);
        //显示视图
        taskPopupWindow.setContentView(popView);
        taskPopupWindow.setBackgroundDrawable(new ColorDrawable(0x8f000000));//全透明背景
        taskPopupWindow.setOutsideTouchable(false);
        taskPopupWindow.setFocusable(true);
        taskPopupWindow.viewSecond=0;//显示5秒，自定义类;
        taskPopupWindow.showAtLocation(outerLinear, Gravity.CENTER,0,0);

    }

    public final class RecordListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public RecordListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return recordJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return recordJSON.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder=new ViewHolder();
                //可以理解为从vlist获取view 之后把view返回给ListView
                convertView =inflater.inflate(R.layout.fragment_check_recorditem, null, false);
                holder.itembtn_delete = convertView.findViewById(R.id.itembtn_delete);
                holder.itembtn_edit = convertView.findViewById(R.id.itembtn_edit);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder)convertView.getTag();
            }
            holder.itembtn_delete.setTag(position);
            holder.itembtn_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (recordJSON.optJSONObject((int)v.getTag()).has("KeyID")&&recordJSON.optJSONObject((int)v.getTag()).has("CheckDeID")){
                        try {
                            TransRecord("Delete","",recordJSON.optJSONObject((int)v.getTag()).getString("KeyID"),recordJSON.optJSONObject((int)v.getTag()).getString("CheckDeID"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        recordJSON.remove((int)v.getTag());
                        recordListAdapter.notifyDataSetChanged();
                    } else {
                        curToast.setText("未找到KeyID,请在GetRecord加入KeyID");
                        curToast.show();
                    }
                    //从后台删除;

                }
            });
            holder.itembtn_edit.setTag(position);
            holder.itembtn_edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        ShowPopMenu(recordJSON.optJSONObject((int)v.getTag()).getString("KeyID"),(int)v.getTag());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            try {
                TextView tv = (TextView) convertView.findViewById(R.id.item_SerNo);// 显示文字
                if (recordJSON.optJSONObject(position).has("SerNo"))
                tv.setText(recordJSON.optJSONObject(position).get("SerNo").toString());
                tv = (TextView) convertView.findViewById(R.id.item_EmpName);// 显示文字
                if (recordJSON.optJSONObject(position).has("EmpName"))
                tv.setText(recordJSON.optJSONObject(position).get("EmpName").toString());
                tv = (TextView) convertView.findViewById(R.id.item_WorkName);// 显示文字
                if (recordJSON.optJSONObject(position).has("WorkName"))
                tv.setText(recordJSON.optJSONObject(position).get("WorkName").toString());
                tv = (TextView) convertView.findViewById(R.id.item_PartName);// 显示文字
                if (recordJSON.optJSONObject(position).has("PartName"))
                tv.setText(recordJSON.optJSONObject(position).get("PartName").toString());
                tv = (TextView) convertView.findViewById(R.id.item_QuestionName);// 显示文字
                if (recordJSON.optJSONObject(position).has("QuestionName"))
                tv.setText(recordJSON.optJSONObject(position).get("QuestionName").toString());
                tv = (TextView) convertView.findViewById(R.id.item_Duty);// 显示文字
                if (recordJSON.optJSONObject(position).has("Duty"))
                tv.setText(recordJSON.optJSONObject(position).get("Duty").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }

        //提取出来方便点
        public final class ViewHolder {
            public Button itembtn_delete;
            public Button itembtn_edit;
        }
    }

    private void ShowPopMenu(final String paramKeyID,final int paramPostion){
        //创建布局
        LayoutInflater inflater=getActivity().getLayoutInflater();
        final View proc_popmenu=inflater.inflate(R.layout.fragment_check_popmenu, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final Button btn_CheckMenu_business=(Button)proc_popmenu.findViewById(R.id.btn_CheckMenu_business);
        final Button btn_CheckMenu_Cut=(Button)proc_popmenu.findViewById(R.id.btn_CheckMenu_Cut);
        final Button btn_CheckMenu_Model=(Button)proc_popmenu.findViewById(R.id.btn_CheckMenu_Model);
        final Button btn_CheckMenu_Storage=(Button)proc_popmenu.findViewById(R.id.btn_CheckMenu_Storage);
        Log.d("BaseKey","BaseKey:"+paramKeyID);
        //创建对话框
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(proc_popmenu).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.v("tag","取消");
            }
        });
        final Dialog dialog = builder.show();
        //菜单事件;
        btn_CheckMenu_business.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TransRecord("Duty","业务",paramKeyID,"");
                try {
                    recordJSON.optJSONObject(paramPostion).put("Duty","业务");
                    recordListAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
        btn_CheckMenu_Cut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TransRecord("Duty","裁剪",paramKeyID,"");
                try {
                    recordJSON.optJSONObject(paramPostion).put("Duty","裁剪");
                    recordListAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
        btn_CheckMenu_Model.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TransRecord("Duty","模板",paramKeyID,"");
                try {
                    recordJSON.optJSONObject(paramPostion).put("Duty","模板");
                    recordListAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
        btn_CheckMenu_Storage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TransRecord("Duty","仓库",paramKeyID,"");
                try {
                    recordJSON.optJSONObject(paramPostion).put("Duty","仓库");
                    recordListAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
    }

    private void TransRecord(String paramCommType,String paramDuty, String keyID,String  checkDeID) {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_OneCheckTransRec @KeyID='" + keyID+ "',@CheckDeID='" + checkDeID
                + "',@CommType='" + paramCommType + "',@Duty='" + paramDuty
                + "',@OperType='TransRecord',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "',@LNG='"+language+"'";
        System.out.println(SqlComm);
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    public final class PartGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public PartGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return typeJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return typeJSON.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_check_part, null, false);
            try {
                TextView tv = (TextView) convertView.findViewById(R.id.item_PartName);// 显示文字
                tv.setText(typeJSON.optJSONObject(position).get("PartName").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }

    public final class PlaceGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public PlaceGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return placeJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return placeJSON.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_check_part, null, false);
            try {
                TextView tv = (TextView) convertView.findViewById(R.id.item_PartName);// 显示文字
                if (placeJSON.optJSONObject(position).has("PlaceName"))
                tv.setText(placeJSON.optJSONObject(position).get("PlaceName").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }

    public final class QuestionGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public QuestionGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return questionJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return questionJSON.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_check_item, null, false);
            try {
                TextView tv = (TextView) convertView.findViewById(R.id.item_QuestionNo);// 显示文字
                tv.setText(questionJSON.optJSONObject(position).get("QuestionNo").toString());
                tv = (TextView) convertView.findViewById(R.id.item_QuestionName);// 显示文字
                tv.setText(questionJSON.optJSONObject(position).get("QuestionName").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }



    public final class ProcGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ProcGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return procJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return procJSON.get(position);
            } catch (JSONException e) {
                System.out.println("getItem取JSON数据出错!");
                e.printStackTrace();
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.fragment_check_listhead, null, false);
            TextView tv;
            int fontColor=getResources().getColor(R.color.text_black);
            try {
                if (procJSON.optJSONObject(position).has("FontColor")) fontColor=procJSON.optJSONObject(position).getInt("FontColor");
                if (procJSON.optJSONObject(position).has("WorkNo")) {
                    tv = (TextView) convertView.findViewById(R.id.txt_item_workno);// 显示文字
                    tv.setText(procJSON.optJSONObject(position).get("WorkNo").toString());
                    tv.setTextColor(fontColor);
                }
                if (procJSON.optJSONObject(position).has("WorkName")) {
                    tv = (TextView) convertView.findViewById(R.id.txt_item_workname);// 显示文字
                    tv.setText(procJSON.optJSONObject(position).get("WorkName").toString());
                    tv.setTextColor(fontColor);
                }
                if (procJSON.optJSONObject(position).has("EmpName")) {
                    tv = (TextView) convertView.findViewById(R.id.txt_item_empname);// 显示文字
                    tv.setText(procJSON.optJSONObject(position).get("EmpName").toString());
                    tv.setTextColor(fontColor);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return convertView;
        }
    }


}